/*
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2023-04-17 12:50:20
 */
//导入数据库实例 便于操作数据库
const db = require('../config/db')
//导入密码加密模块
const bcrypt = require('../dao/bcrypt')
//导入token
const jwts = require('../dao/jwt')

//导入token中间件
// const jwt = require('jsonwebtoken')

let serverToken = null

//注册用户
exports.regUser = (req, res) => {
    //邮箱判定规则
    let sql1, sql2
    let reg = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/
    let { username, password, email } = req.body
    if (reg.test(email)) {  //判断邮箱地址是否输入正确
        sql1 = 'select * from user where email = ?';

    } else return res.sendMsg('邮箱地址输入不正确', 400)

    sql2 = 'select * from user where username = ?'
    //检测邮箱是否有注册的重复数据
    db.query(sql1, email, (err, result) => {
        if (err)
            return res.sendMsg(err, 500)
        else if (result.length > 0)
            return res.sendMsg('邮箱已被注册,请更换其他邮箱', 400)
        else {  //检测用户名
            db.query(sql2, username, (err1, result1) => {
                if (err1)
                    return res.sendMsg(err1, 400)
                else if (result1.length > 0)
                    return res.sendMsg('用户名已被注册,请更换其他用户名', 400)
                else {
                    const insert = 'insert into user set ?'
                    //对用户输入的密码进行加密并返回加密密码
                    password = bcrypt.encryption(password)
                    db.query(insert, { username: username, password: password, email: email, registerTime: new Date() }, (err, result) => {
                        if (err)
                            return res.sendMsg(err, 400)
                        if (result.affectedRows != 1)  //SQL 语句执行成功，但影响行数不为 1
                            return res.sendMsg('注册新用户失败', 400)
                        else return res.sendMsg('用户注册成功', 200)
                    })
                }
            })
        }
    })
}

//用户登录
exports.login = (req, res) => {
    let { users, password } = req.body
    let reg = /^([a-zA-Z\d][\w-]{2,})@(\w{2,})\.([a-z]{2,})(\.[a-z]{2,})?$/
    let sql = null
    if (reg.test(users)) {  //如果使用邮箱登录
        sql = 'select * from user where email = ?';
    } else {
        sql = 'select * from user where username = ?';
    }
    db.query(sql, users, (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.length != 1) return res.sendMsg('登录失败,不存在该用户', 400)
        //剔除密码
        let returnResut = {
            userid: result[0].userid,
            username: result[0].username,
            email: result[0].email,
            birth: result[0].birth,
            explain: result[0].explain,
            imgurl: result[0].imgurl,
            phone: result[0].phone,
            registerTime: result[0].registerTime,
            sex: result[0].sex,
        }
        //检测输入的密码是否一致
        const compareResult = bcrypt.verification(password, result[0].password)
        if (!compareResult) {
            return res.sendMsg('输入密码错误！', 400)
        }
        //输入的密码正确,生成token字符串
        //获取用户信息并剔除密码和头像信息
        const userinfo = { ...result[0], password: '', imgurl: '' }
        serverToken = jwts.generateToken(userinfo)
        //将生成的token响应给客户端
        res.send({
            code: 200,
            message: 'success',
            token: serverToken,
            data: returnResut
        })
    })
}

//验证登录用户密码的正确性
exports.checkPwd = (req, res) => {
    let { userid, password } = req.body
    let sql = 'select password from user where userid = ?';
    db.query(sql, userid, (err, result) => {
        if (err) return res.sendMsg(err, 500)
        if (result.length != 1) return res.sendMsg('不存在该用户', 400)
        else {
            //检测输入的密码是否一致
            const compareResult = bcrypt.verification(password, result[0].password)
            if (!compareResult) {
                return res.sendMsg('密码验证失败', 400)
            } else {
                return res.sendMsg('密码验证成功', 200)
            }
        }
    })
}

//验证客户端传递的token是否正确  解码
exports.verifToken = (req, res) => {
    let token = req.headers.token
    //返回解析之后的token
    let { verifytoken } = jwts.verifyToken(token)
    if (verifytoken == 1) {//token验证正确 
        console.log('token验证成功');
    } else {
        console.log('token验证失败');
        res.sendMsg('token验证失败', 304)
    }
    // console.log('verify', verifytoken);
    // res.sendMsg('token验证正确', 200, result)


    // //判断客户端传入的token是否和服务器的token一致  //token解码
    // jwt.verify(token, secret.secretKey, (err, decode) => {
    //     if (err) { //token失效
    //         return res.sendMsg('token失效', 304)
    //     } else {
    //         //创建token时，使用的数据
    //         console.log(decode);
    //         res.send(decode)
    //     }
    // })
}

